package com.ruoyi.fun.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fun.domain.EcUserCoupon;
import com.ruoyi.fun.domain.EcUserCouponNew;
import com.ruoyi.fun.service.IEcUserCouponService;
import com.ruoyi.fun.service.IEcUserCouponNewService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户优惠券Controller
 * 
 * @author ruoyi
 * @date 2025-08-15
 */
@RestController
@RequestMapping("/fun/userCoupon")
public class EcUserCouponController extends BaseController
{
    @Autowired
    private IEcUserCouponService ecUserCouponService;
    
    @Autowired
    private IEcUserCouponNewService ecUserCouponNewService;

    /**
     * 查询用户优惠券列表
     */
    @PreAuthorize("@ss.hasPermi('fun:coupon:list')")
    @GetMapping("/list")
    public TableDataInfo list(EcUserCoupon ecUserCoupon)
    {
        startPage();
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        ecUserCoupon.setOrgId(orgId);
        List<EcUserCoupon> list = ecUserCouponService.selectEcUserCouponList(ecUserCoupon);
        return getDataTable(list);
    }

    /**
     * 导出用户优惠券列表
     */
    @PreAuthorize("@ss.hasPermi('fun:coupon:export')")
    @Log(title = "用户优惠券", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EcUserCoupon ecUserCoupon)
    {
        List<EcUserCoupon> list = ecUserCouponService.selectEcUserCouponList(ecUserCoupon);
        ExcelUtil<EcUserCoupon> util = new ExcelUtil<EcUserCoupon>(EcUserCoupon.class);
        util.exportExcel(response, list, "用户优惠券数据");
    }

    /**
     * 获取用户优惠券详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:coupon:query')")
    @GetMapping(value = "/{userCouponId}")
    public AjaxResult getInfo(@PathVariable("userCouponId") Long userCouponId)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        return success(ecUserCouponService.selectEcUserCouponByUserCouponIdAndOrgId(userCouponId, orgId));
    }

    /**
     * 新增用户优惠券
     */
    @PreAuthorize("@ss.hasPermi('fun:coupon:add')")
    @Log(title = "用户优惠券", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EcUserCoupon ecUserCoupon)
    {
        ecUserCoupon.setOrgId(getOrgId());
        return toAjax(ecUserCouponService.insertEcUserCoupon(ecUserCoupon));
    }

    /**
     * 修改用户优惠券
     */
    @PreAuthorize("@ss.hasPermi('fun:coupon:edit')")
    @Log(title = "用户优惠券", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EcUserCoupon ecUserCoupon)
    {
        return toAjax(ecUserCouponService.updateEcUserCoupon(ecUserCoupon));
    }

    /**
     * 删除用户优惠券
     */
    @PreAuthorize("@ss.hasPermi('fun:coupon:remove')")
    @Log(title = "用户优惠券", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userCouponIds}")
    public AjaxResult remove(@PathVariable Long[] userCouponIds)
    {
        return toAjax(ecUserCouponService.deleteEcUserCouponByUserCouponIds(userCouponIds));
    }

    /**
     * 核验优惠券
     */
    @Log(title = "核验优惠券", businessType = BusinessType.UPDATE)
    @PostMapping("/verify")
    public AjaxResult verifyCoupon(@RequestBody java.util.Map<String, Object> requestData)
    {
        try {
            String verifyCode = (String) requestData.get("verifyCode");
            if (verifyCode == null || verifyCode.trim().isEmpty()) {
                return AjaxResult.success().put("success", 0).put("msg", "校验失败，使用了错误的优惠券验证码或优惠券不存在");
            }
            
            // 解析验证码格式：优惠券码_用户优惠券ID
            String[] parts = verifyCode.split("_");
            if (parts.length != 2) {
                return AjaxResult.success().put("success", 0).put("msg", "校验失败，使用了错误的优惠券验证码或优惠券不存在");
            }
            
            String couponCode = parts[0];
            Long userCouponId;
            try {
                userCouponId = Long.parseLong(parts[1]);
            } catch (NumberFormatException e) {
                return AjaxResult.success().put("success", 0).put("msg", "校验失败，使用了错误的优惠券验证码或优惠券不存在");
            }
            
            // 查询用户优惠券（不限制组织ID）
            EcUserCoupon userCoupon = ecUserCouponService.selectEcUserCouponByUserCouponId(userCouponId);
            if (userCoupon == null) {
                return AjaxResult.success().put("success", 0).put("msg", "校验失败，使用了错误的优惠券验证码或优惠券不存在");
            }
            
            // 验证优惠券码是否匹配
            if (!couponCode.equals(userCoupon.getCouponCode())) {
                return AjaxResult.success().put("success", 0).put("msg", "校验失败，使用了错误的优惠券验证码或优惠券不存在");
            }
            
            // 检查使用状态
            if (userCoupon.getUseStatus() != null && "1".equals(userCoupon.getUseStatus())) {
                return AjaxResult.success().put("success", 0).put("msg", "该优惠券已经被核验过，无法再进行核验");
            }
            
            // 更新使用状态为已使用
            userCoupon.setUseStatus("1");
            userCoupon.setUsedTime(new java.util.Date());
            
            int result = ecUserCouponService.updateEcUserCoupon(userCoupon);
            if (result > 0) {
                return AjaxResult.success().put("success", 1).put("msg", "优惠券核验成功");
            } else {
                return AjaxResult.success().put("success", 0).put("msg", "校验失败，使用了错误的优惠券验证码或优惠券不存在");
            }
        } catch (Exception e) {
            return AjaxResult.success().put("success", 0).put("msg", "校验失败，使用了错误的优惠券验证码或优惠券不存在");
        }
    }

    /**
     * 根据userCouponId和组织ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:coupon:query')")
    @GetMapping(value = "/{userCouponId}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("userCouponId") Long userCouponId, @PathVariable("orgId") Long orgId)
    {
        return success(ecUserCouponService.selectEcUserCouponByUserCouponIdAndOrgId(userCouponId, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('fun:coupon:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcUserCoupon ecUsercoupon = new EcUserCoupon();
        List<EcUserCoupon> list = ecUserCouponService.selectEcUserCouponListByOrgId(ecUsercoupon, orgId);
        return getDataTable(list);
    }

    /**
     * APP端获取用户优惠券列表
     */
    @GetMapping("/app/list")
    public TableDataInfo getAppUserCouponList(EcUserCoupon ecUserCoupon, Long orgId)
    {
        startPage();
        // 如果前端没有传递orgId，则使用BaseController的getOrgId()方法
        if (orgId == null) {
            orgId = getOrgId();
        }
        Long userId = getUserId();
        System.out.println("=== 优惠券查询调试信息 ===");
        System.out.println("当前用户ID: " + userId);
        System.out.println("当前组织ID: " + orgId);
        System.out.println("前端传递的orgId参数: " + ecUserCoupon.getOrgId());
        List<EcUserCoupon> list = ecUserCouponService.selectEcUserCouponListByUserIdAndOrgId(userId, orgId);
        System.out.println("查询到的优惠券数量: " + (list != null ? list.size() : 0));
        
        // 为每个用户优惠券补充详细信息
        if (list != null && !list.isEmpty()) {
            for (EcUserCoupon userCoupon : list) {
                if (userCoupon.getCouponId() != null) {
                        // 根据couponId从EcUserCouponNew表中获取优惠券详细信息
                        EcUserCouponNew userCouponDetail = ecUserCouponNewService.selectEcUserCouponNewByCouponId(userCoupon.getCouponId());
                        if (userCouponDetail != null) {
                        // 将详细信息设置到用户优惠券对象中
                            userCoupon.setCouponName(userCouponDetail.getCouponName());
                            userCoupon.setCouponType(userCouponDetail.getCouponType());
                            userCoupon.setCouponAmount(userCouponDetail.getCouponAmount());
                            userCoupon.setDiscountRate(userCouponDetail.getDiscountRate());
                            userCoupon.setMinAmount(userCouponDetail.getMinAmount());
                            userCoupon.setMaxAmount(userCouponDetail.getMaxAmount());
                        userCoupon.setExpireTime(userCouponDetail.getExpireTime());
                         userCoupon.setSource(userCouponDetail.getSource());
                         userCoupon.setRemark(userCouponDetail.getRemark());
                    }
                }
            }
            System.out.println("第一个优惠券信息（含详细信息）: " + list.get(0));
        }
        System.out.println("=== 调试信息结束 ===");
        return getDataTable(list);
    }
    
    /**
     * APP端根据订单号查询优惠券（无需权限验证）
     */
    @GetMapping("/app/getByOrderNo")
    public AjaxResult getAppCouponByOrderNo(String orderNo, Long orgId)
    {
        // 如果前端没有传递orgId，则使用BaseController的getOrgId()方法
        if (orgId == null) {
            orgId = getOrgId();
        }
        Long userId = getUserId();
        System.out.println("根据订单号查询优惠券 - userId: " + userId + ", orgId: " + orgId + ", orderNo: " + orderNo);
        
        // 根据订单号查询优惠券
        EcUserCoupon userCoupon = ecUserCouponService.selectEcUserCouponByOrderNo(orderNo, userId, orgId);
        if (userCoupon != null) {
            // 为优惠券补充详细信息
            if (userCoupon.getCouponId() != null) {
                    EcUserCouponNew userCouponDetail = ecUserCouponNewService.selectEcUserCouponNewByCouponId(userCoupon.getCouponId());
                    if (userCouponDetail != null) {
                        userCoupon.setCouponName(userCouponDetail.getCouponName());
                        userCoupon.setCouponType(userCouponDetail.getCouponType());
                        userCoupon.setCouponAmount(userCouponDetail.getCouponAmount());
                        userCoupon.setDiscountRate(userCouponDetail.getDiscountRate());
                        userCoupon.setMinAmount(userCouponDetail.getMinAmount());
                        userCoupon.setMaxAmount(userCouponDetail.getMaxAmount());
                    userCoupon.setExpireTime(userCouponDetail.getExpireTime());
                     userCoupon.setSource(userCouponDetail.getSource());
                     userCoupon.setRemark(userCouponDetail.getRemark());
                }
            }
            return success(userCoupon);
        }
        return success(null);
    }

    /**
     * APP端使用优惠券（无需权限验证）
     */
    @PostMapping("/app/use/{userCouponId}")
    public AjaxResult useAppUserCoupon(@PathVariable("userCouponId") Long userCouponId, @RequestBody(required = false) java.util.Map<String, Object> requestData)
    {
        Long userId = getUserId();
        
        // 从请求参数中获取组织ID，支持字符串转换
        Long orgId = null;
        if (requestData != null && requestData.containsKey("orgId")) {
            Object orgIdObj = requestData.get("orgId");
            if (orgIdObj instanceof String) {
                orgId = Long.parseLong((String) orgIdObj);
            } else if (orgIdObj instanceof Number) {
                orgId = ((Number) orgIdObj).longValue();
            }
        }
        
        // 如果没有传入orgId，使用默认值或从用户信息获取
        if (orgId == null) {
            orgId = getOrgId(); // 从当前用户获取组织ID
        }
        
        System.out.println("使用优惠券 - userId: " + userId + ", orgId: " + orgId + ", userCouponId: " + userCouponId);
        
        // 查询用户优惠券
        EcUserCoupon userCoupon = ecUserCouponService.selectEcUserCouponByUserCouponIdAndOrgId(userCouponId, orgId);
        if (userCoupon == null || !userCoupon.getUserId().equals(userId)) {
            System.out.println("优惠券查询失败 - userCoupon: " + userCoupon + ", userId: " + userId);
            return error("优惠券不存在或无权限访问");
        }
        
        // 检查优惠券状态
        if (!"0".equals(userCoupon.getUseStatus())) {
            return error("优惠券已使用或已过期");
        }
        
        // 更新优惠券状态为已使用
        userCoupon.setUseStatus("1");
        
        // 设置使用时间和订单号
        if (requestData != null) {
            String orderId = (String) requestData.get("orderId");
            String useTimeStr = (String) requestData.get("useTime");
            
            if (orderId != null) {
                userCoupon.setOrderNo(orderId);
            }
            
            if (useTimeStr != null) {
                try {
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                    sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
                    userCoupon.setUsedTime(sdf.parse(useTimeStr));
                } catch (java.text.ParseException e) {
                    // 如果解析失败，使用当前时间
                    userCoupon.setUsedTime(new java.util.Date());
                }
            } else {
                userCoupon.setUsedTime(new java.util.Date());
            }
        } else {
            userCoupon.setUsedTime(new java.util.Date());
        }
        
        int result = ecUserCouponService.updateEcUserCoupon(userCoupon);
        System.out.println("优惠券使用结果: " + result);
        return toAjax(result);
    }

}

